﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;

namespace Eneta.Portal.NewsAndBlogs
{
    public static class Utility
    {
        public static Control FindControl(this Control control, string name, bool recursive)
        {
            if (!recursive)
                return control.FindControl(name);

            foreach (Control child in control.Controls)
            {
                if (child.ID == name)
                    return child;
                var ctl = child.FindControl(name, recursive);
                if (ctl != null)
                    return ctl;
            }
            return null;
        }

        public static SPListItem GetUserProfile(this SPUser user)
        {
            SPListItem item = null;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                var siteId = user.ParentWeb.Site.ID;
                using(var site = new SPSite(siteId))
                using (var web = site.OpenWeb())
                {
                    string queryString =
                        "<Where><Eq><FieldRef Name=\"SysID\" /><Value Type=\"Text\">{0}</Value></Eq></Where>";
                    queryString = string.Format(queryString, user.ToString().Substring(7));

                    var query = new SPQuery();
                    query.Query = queryString;

                    var items = web.Lists["ProfileList"].GetItems(query);
                    if (items.Count == 0)
                        return;
                    item = items[0];
                }
            });

            return item;
        }

    }
}